package net.bingosoft.common.struts.tags;

import java.util.Iterator;

import javax.servlet.jsp.JspException;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.taglib.TagUtils;
import org.apache.struts.taglib.html.Constants;
import org.apache.struts.taglib.html.SelectTag;
/**
 * 2007-8-20 下午07:38:23
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:struts的下拉框标签,自动处理验证错误
 * ChangeLog:
 */
public class StrutsSelectTag extends SelectTag{

	private static final long serialVersionUID = 1L;
	private boolean appendError = true;
	private boolean required = false; //该项是否为必填项
	
	private String dataType;
	private String message;
	
    public String getDataType() {
		return dataType;
	}
	public void setDataType(String dataType) {
		this.dataType = dataType;
		if("Required".equals(dataType)){
			this.required = true;
		}
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public void setRequired(boolean required) {
		this.required = required;
		if(this.required && this.dataType == null){
			this.dataType = "Required";
		}
	}
	/**
     * Render the end of this form.
     *
     * @exception JspException if a JSP exception has occurred
     */
    public int doEndTag() throws JspException {

        // Remove the page scope attributes we created
        pageContext.removeAttribute(Constants.SELECT_KEY);

        // Render a tag representing the end of our current form
        StringBuffer results = new StringBuffer();
        if (saveBody != null) {
            results.append(saveBody);
            saveBody = null;
        }
        results.append("</select>");
        //------------------------
		//是否在text标签后面扩展对应的验证错误
		if(appendError){
			results = appendError(results);
		}
		if(required){
			results = appendRequiredFlag(results);
		}
        //------------------------

        TagUtils.getInstance().write(pageContext, results.toString());

        return (EVAL_PAGE);
    }
    /**
     * 'Hook' to enable tags to be extended and 
     *  additional attributes added.
     * @param handlers The StringBuffer that output will be appended to.
     */
    protected void prepareOtherAttributes(StringBuffer handlers) {
    	prepareAttribute(handlers, "DataType", dataType); 
    	prepareAttribute(handlers, "Message", message);
    	prepareAttribute(handlers, "required", required); 
    }
    /**
     * 扩展对应的错误信息
     * @param results
     * @return
     * @throws JspException 
     */
    protected StringBuffer appendError(StringBuffer results) throws JspException{
    	ActionMessages errors = TagUtils.getInstance().getActionMessages(pageContext, Globals.ERROR_KEY);
		if (errors != null && !errors.isEmpty()) {
			String errorHeader = TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,"errors.header");
			String errorFooter = TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,"errors.footer");
			if(errorHeader == null){
				//struts验证出错信息前缀
				errorHeader ="<br/><font color='red'>";
			}
			if(errorHeader == null){
				//struts验证出错信息后缀
				errorFooter ="</font>";
			}
			Iterator it = errors.get(property);
			while(it.hasNext()){
				ActionMessage error = (ActionMessage)it.next();
				String errorMsg = "";
				if (error.isResource()) {
					errorMsg = TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,error.getKey(),error.getValues());
				} else {
					errorMsg = error.getKey();
				}
				results.append(errorHeader).append(errorMsg).append(errorFooter);
			}
		}
		return results;
    }
	/**
	 * 扩展必填项标志
	 * @param buffer
	 * @return
	 * @throws JspException
	 */
	private StringBuffer appendRequiredFlag(StringBuffer buffer) throws JspException{
		String requiredFlag =  TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,"flag.required");
		if(requiredFlag == null){
			requiredFlag = "<span style='color: red;vertical-align: middle;'> * </span>";
		}
		return buffer.append(requiredFlag);
	}
	public boolean isAppendError() {
		return appendError;
	}
	public void setAppendError(boolean appendError) {
		this.appendError = appendError;
	}

}
